// function xh(nodeName, attrs, ...children) {
//     const $el = document.createElement(nodeName);
//     for( let key in attrs) {
//         $el.setAttribute(key, attrs[key]);
//     }
//     children.forEach(child => {
//         if ( typeof child === 'string') {
//             $el.appendChild(document.createTextNode(children))
//         } else {
//             $el.appendChild(child)
//         }
//     })
//     return $el;
// }

// 生成 vnode
function h(nodeName, attrs, ...children) {
    return {nodeName, attrs, children}
}
// vnode => Dom
const renderNode = vnode => {
    let el;
    const {nodeName, attributes, children } =  vnode;
    if (vnode.split) return document.createTextNode(vnode);
    el = document.createElement(nodeName); 
    for( let key in attributes) {
        el.setAttribute(key, attrs[key]);
    }
    (children || []).forEach(child => {
        el.appendChild(renderNode(child))
    })
    return el;    
}
// 应用产生 vdom
const App = (props) => {
    const { list } = props;
    return h('div', { class: 'app' }, 
        h('h1', null, 'Simple vDom'),
        h('ul', null, ...list.map(item => h('li', null, item)))
    )
}
// 综合 
let currentApp;
const render = (state) => {
    const newApp = renderNode(App(state));
    currentApp ? document.body.replaceChild(newApp, currentApp)
               : document.body.appendChild(newApp);
    currentApp = newApp;
}

function getRandomColor (arr, num = 5)  {
    let arrLength = arr.length;
    let tmp = []
    for(let i = 0; i < num; i++) {
        tmp.push(arr[Math.floor(Math.random()*arrLength)])
    }
    return tmp;
}
const colors = ['red', 'green', 'blue', 'gray', 'pink', 'purple', 'yellow','orange'];
const state = {
    list: getRandomColor(colors)
}
setInterval(function() { 
    render({
        list: getRandomColor(colors)
    })
}, 500)
